const prisma = require('../utils/prisma');
const { success, error } = require('../utils/response');

/**
 * 获取消息列表
 * @route GET /api/messages
 */
const getMessages = async (req, res) => {
  try {
    const messages = await prisma.message.findMany({
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    });
    
    return success(res, messages);
  } catch (err) {
    console.error('Get messages error:', err);
    return error(res, 'Failed to get messages', 500);
  }
};

/**
 * 获取指定消息
 * @route GET /api/messages/:id
 */
const getMessageById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const message = await prisma.message.findUnique({
      where: { id },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      }
    });
    
    if (!message) {
      return error(res, 'Message not found', 404);
    }
    
    return success(res, message);
  } catch (err) {
    console.error('Get message error:', err);
    return error(res, 'Failed to get message', 500);
  }
};

/**
 * 创建消息
 * @route POST /api/messages
 */
const createMessage = async (req, res) => {
  try {
    const { content } = req.body;
    const userId = req.user.id;
    
    if (!content) {
      return error(res, 'Content is required', 400);
    }
    
    // 创建消息
    const message = await prisma.message.create({
      data: {
        content,
        userId,
        read: false
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      }
    });
    
    return success(res, message, 'Message created successfully', 201);
  } catch (err) {
    console.error('Create message error:', err);
    return error(res, 'Failed to create message', 500);
  }
};

/**
 * 更新消息
 * @route PUT /api/messages/:id
 */
const updateMessage = async (req, res) => {
  try {
    const { id } = req.params;
    const { content, read } = req.body;
    
    // 检查消息是否存在
    const existingMessage = await prisma.message.findUnique({
      where: { id }
    });
    
    if (!existingMessage) {
      return error(res, 'Message not found', 404);
    }
    
    // 检查权限（只有管理员或消息所有者可以更新内容）
    if (content && req.user.role !== 'admin' && req.user.id !== existingMessage.userId) {
      return error(res, 'Permission denied', 403);
    }
    
    // 准备更新数据
    const updateData = {};
    
    if (content) updateData.content = content;
    if (read !== undefined) updateData.read = read;
    
    // 更新消息
    const updatedMessage = await prisma.message.update({
      where: { id },
      data: updateData,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      }
    });
    
    return success(res, updatedMessage, 'Message updated successfully');
  } catch (err) {
    console.error('Update message error:', err);
    return error(res, 'Failed to update message', 500);
  }
};

/**
 * 删除消息
 * @route DELETE /api/messages/:id
 */
const deleteMessage = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查消息是否存在
    const existingMessage = await prisma.message.findUnique({
      where: { id }
    });
    
    if (!existingMessage) {
      return error(res, 'Message not found', 404);
    }
    
    // 检查权限（只有管理员或消息所有者可以删除）
    if (req.user.role !== 'admin' && req.user.id !== existingMessage.userId) {
      return error(res, 'Permission denied', 403);
    }
    
    // 删除消息
    await prisma.message.delete({
      where: { id }
    });
    
    return success(res, null, 'Message deleted successfully');
  } catch (err) {
    console.error('Delete message error:', err);
    return error(res, 'Failed to delete message', 500);
  }
};

module.exports = {
  getMessages,
  getMessageById,
  createMessage,
  updateMessage,
  deleteMessage
};
